$(function () {
		var emojiPairs = [
			['☀', '☀'],
			['✨', '✨'],			
			['✡', '✡'],
			['⚪', '⚪'],
			['⚫', '⚫'], 
			['❤', '❤']
			/*['💥', '💥']
			['🔴', '🔴']*/
		];
		var rich_articles = new Array();
		var text_articles = new Array();
		var entry_type = '1';// 1:文本内容 2：跳转链接

        var menu = function () {
            this.$btn;
            this.listen();
        };

        menu.prototype.listen = function () {
            var self = this;
            $('.mobile-footer').on('click', 'li a', function () {
                self.$btn = $(this);
                self.$btn.parent('li').hasClass('menu-add') ? self.add() : self.checkShow();
            }).find('li:first a:first').trigger('click');
            $('.menu-delete').on('click', function () {
				if (!confirm('确认要执行该操作吗?删除后菜单下设置的内容将被删除！')) {
					return false;
				}
				self.del();
				//updateAlert('删除后菜单下设置的内容将被删除！', 'info');
				/**
                var index = $.msg.confirm('删除后菜单下设置的内容将被删除！', function () {
                    self.del(), $.msg.close(index);
                });
				**/
            });
            $('.menu-submit').on('click', function () {
                self.submit();
            });
			

			//生成跳转链接
			$(document).on('click', '[data-toggle="create-referral-link"]', function () {
				GetReferralLinkModal.instance.inputUrlCallback = function (url) {
					$("#menu-customizeurl").val(url);
					$("#menu-customizeurl").keyup();
				};
				GetReferralLinkModal.instance.open({});
			});


			//图文配置---自定义标题
			$(document).on('click', '[data-toggle="editMainTitle"]', function () {
				
				var title=$("#graphic-title").text();
				var url = $("#graphic-url").text();
				var description= $("#graphic-description").text();
				EditSubArticleModal.instance.open({
					subject: '修改',
					title: title,
					url: url,
					description: description,
					forbidEnterTitle: true,
					messageType: 1,
					descriptionVisible: true,
					callbacks: {
						submit: function (data) {
							$("#graphic-title").text(data.title);
							$("#graphic-description").text(data.description);
							$("#graphic-url").text(data.url);
							if (rich_articles.length>0)
							{
								rich_articles[0].title = data.title;
								rich_articles[0].description = data.description;
								rich_articles[0].url = data.url;
							}else{
								rich_articles.push({
									title: data.title,
									description: data.description,
									url: data.url,
									picurl:''
								});
							}
							
							var param = JSON.stringify(rich_articles);
							self.$btn.find('span').attr('data-rich_articles',param);
							
						}
					}
				});
			});

			
			//图文配置---图片
			
			$(document).on('click', '[data-toggle="editArticlePic"]', function () {
				var picurl = $("#graphic-picurl").attr("src");
				
				ChoosePicModal.instance.open({
					picurl: picurl,
					callbacks: {
						submit: function (url, contains_vip_resource) {
							$("#graphic-picurl").attr("src",url);
							rich_articles[0]['picurl'] = url;
							var param = JSON.stringify(rich_articles);
							self.$btn.find('span').attr('data-rich_articles',param);
						}
					}
				});
			});
			
			//文字配置
			$(document).on('click', '[data-toggle="editSubArticle"]', function () {
				
				if (entry_type==2)
				{
					var index = $(this).attr("data-index") || '0';
					var title=$("#text-title-"+index).text();
					var url = $("#text-url-"+index).text();
				}else{
					var index = 0;
					var title=$("#text-title").text();
					var url = $("#text-url").text();
				}
				console.log("entry_type"+entry_type);
				EditSubArticleModal.instance.open({
					text_title: title,
					title: title,
					url: url,
					forbidEnterTitle: true,
					messageType: 2,
					entry_type: entry_type,
					callbacks: {
						submit: function (data) {
							entry_type = data.entry_type;
							self.$btn.find('span').attr('data-entry_type',data.entry_type);
							//console.log("entry_type----"+entry_type);
							//console.log(text_articles);

							if (entry_type==2)
							{
								$("#text-add-sub").show();
								text_articles[index].title =data.title;
								text_articles[index].description = data.description;
								text_articles[index].url = data.url;
							}else{
								$("#text-add-sub").hide();
								$("#text-title").text(data.title);
								$("#text-url").text(data.url);
								text_articles = new Array();
								text_articles.push({
									title: data.title,
									description: data.description,
									url: data.url
								});
							}
							renderChange();
							var param = JSON.stringify(text_articles);
							self.$btn.find('span').attr('data-text_articles',param);
						}
					}
				});
				
			});

			//添加文本
			$(document).on('click', '[data-toggle="addSubArticle"]', function () {
				var total = text_articles.length;
				if (total>7)
				{
					$("#text-msg").show();
					return false;
				}else{
					$("#text-msg").hide();
				}
				text_articles.push({
					title: "自定义文本",
					description: '',
					url: ''
				});
				renderChange();
			});
			//删除文本
			$(document).on('click', '#text-remove', function () {
				var index = $(this).attr("data-index");
				text_articles.splice(index, 1);
				renderChange();
			});
			//上移
			$(document).on('click', '#text-upSub', function () {
				var idx = $(this).attr("data-index");
				if ((text_articles.length > 1) && (idx > 0)) {
					text_articles[idx] = text_articles.splice(idx - 1, 1, text_articles[idx])[0];
					var param = JSON.stringify(text_articles);
					self.$btn.find('span').attr('data-text_articles',param);
					renderChange();
				}
			});
			// 下移
			$(document).on('click', '#text-downSub', function () {
				var idx = $(this).attr("data-index");
				if ((text_articles.length > 1) && (idx < text_articles.length - 1)) {
					text_articles[idx] = text_articles.splice(idx + 1, 1, text_articles[idx])[0];
					var param = JSON.stringify(text_articles);
					self.$btn.find('span').attr('data-text_articles',param);
					renderChange();
				}
			});
			//选择按钮样式
			$(document).on('change', '#menu-style', function () {
				var text = $(this).val();
				$("#menu-name").val(text);
				$("#menu-name").keyup();
			});

			//上传图片
			$(document).on('click', '#imageupload', function () {
				var url = "/admin/wxmp/upload_image";
				var maxFileSize = 512 * 1024;
				var options = {
					url: url,
					dataType: 'json',
					add: function (e, data) {
						var file = data.files[0];
						if (!(/\.(jpg|jpeg|png|gif)$/i).test(file.name)) {
							updateAlert('请选择图片文件', 'error');
							return false;
						}
						if (file.size > maxFileSize) {
							updateAlert('图片必须小于' + (maxFileSize / 1024) + 'KB', 'error');
							return false;
						}
						data.submit();
					},
					done: function (e, data) {
						//valueAccessor()(data.result.url);
						if (data.result.status==1)
						{
							self.$btn.find('span').attr('data-msg_cover',data.result.info.url);

							$("#msg-cover").attr("src",data.result.info.url)
							updateAlert('上传成功', 'success');
						}else{
							updateAlert('上传失败', 'error');
						}
					},
					fail: function (e, data) {
						handleAjaxError(data.jqXHR);
					}
				};
				$(this).fileupload(options);
			});
        };

        menu.prototype.add = function () {
            var $add = this.$btn.parent('li'), $ul = $add.parent('ul');
            if ($ul.hasClass('mobile-footer')) { /* 添加一级菜单 */
                var $li = $('<li class="parent-menu"><a class="active"><i class="icon-sub hide"></i> <span>一级菜单</span></a></li>').insertBefore($add);
                this.$btn = $li.find('a');
                $('<div class="sub-menu text-center hide"><ul><li class="menu-add"><a><i class="icon-add"></i></a></li></ul><i class="arrow arrow_out"></i><i class="arrow arrow_in"></i></div>').appendTo($li);
            } else { /* 添加二级菜单 */
                this.$btn = $('<li><a class="bottom-border"><span>二级菜单</span></a></li>').prependTo($ul).find('a');
            }
            this.checkShow();
        };

        menu.prototype.checkShow = function () {
            var $li = this.$btn.parent('li'), $ul = $li.parent('ul');
            /* 选中一级菜单时显示二级菜单 */
            if ($li.hasClass('parent-menu')) {
                $('.parent-menu .sub-menu').not(this.$btn.parent('li').find('.sub-menu').removeClass('hide')).addClass('hide');
            }

            /* 一级菜单添加按钮 */
            var $add = $('li.parent-menu:last');			
            $add.siblings('li').size() >= 3 ? $add.addClass('hide') : $add.removeClass('hide');
            /* 二级菜单添加按钮 */
            $add.siblings('li').map(function () {
                var $add = $(this).find('ul li:last');
                $add.siblings('li').size() >= 5 ? $add.addClass('hide') : $add.removeClass('hide');
            });
            /* 处理一级菜单 */
            var parentWidth = 100 / $('li.parent-menu:visible').size() + '%';
            $('li.parent-menu').map(function () {
                var $icon = $(this).find('.icon-sub');
                $(this).width(parentWidth).find('ul li').size() > 1 ? $icon.removeClass('hide') : $icon.addClass('hide');
            });
            /* 更新选择中状态 */
            $('.mobile-footer a.active').not(this.$btn.addClass('active')).removeClass('active');
            this.renderEdit();
			this.changeStyle();
            return $ul;
        };
	
		//按钮样式
		menu.prototype.changeStyle = function () { 
			var $span = this.$btn.find('span');

			var rcjk = /[\u2E80-\u2EFF\u2F00-\u2FDF\u3000-\u303F\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FBF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF]+/g;
			var match = rcjk.exec($span.text());

			var html = '<option value="'+match[0]+'">无样式</option>';
			for (var i = 0; i < emojiPairs.length; i++) {
                var left = emojiPairs[i][0];
                var right = emojiPairs[i][1];
				var value = left + '%s' + right;
				var select = $span.attr('data-style');
				
				var text = left + match[0] + right;
				if (text==select)
				{
					html +='<option value="'+text+'" selected>'+text+'</option>'; 
				}else{
					html +='<option value="'+text+'">'+text+'</option>'; 
				}
				
            }
			
			$("#menu-style").html(html);
		};

        menu.prototype.del = function () {
            var $li = this.$btn.parent('li'), $ul = $li.parent('ul');
            var $default = function () {
                if ($li.prev('li').size() > 0) {
                    return $li.prev('li');
                }
                if ($li.next('li').size() > 0 && !$li.next('li').hasClass('menu-add')) {
                    return $li.next('li');
                }
                if ($ul.parents('li.parent-menu').size() > 0) {
                    return $ul.parents('li.parent-menu');
                }
                return $('null');
            }.call(this);
            $li.remove();
            this.$btn = $default.find('a:first');
            this.checkShow();
        };

        menu.prototype.renderEdit = function () {
            var $span = this.$btn.find('span'), $li = this.$btn.parent('li'), $ul = $li.parent('ul'), $html = '';
            if ($li.find('ul li').size() > 1) { /*父菜单*/
                $html = $($('.menu-editor-parent-tpl').html());
                $html.find('input[name="menu-name"]').val($span.text()).on('change keyup', function () {
                    $span.text(this.value || ' ');
                });
                $('.menu-editor .menu-content').html($html);
            } else {
				
                $html = $($('.menu-editor-content-tpl').html());
                $html.find('input[name="menu-name"]').val($span.text()).on('change keyup', function () {
                    $span.text(this.value || ' ');
					$span.attr('data-style',this.value);
                });
                $('.menu-editor .menu-content').html($html);
				/**
                var type = $span.attr('data-type') || 'text';
				
				$html.find('#menu-type').val(type);				

                $html.find('#menu-type').on('click', function () {
                    $span.attr('data-type', this.value || 'text');
					var type = this.value;
					var $input = $html.find('input,select');
					$input.on('change keyup click', function () {
						// 将input值写入到span上
						$span.data(this.name, $(this).val());
					});
                });***/

				//消息类型
				var message_type = $span.attr('data-message_type') || 1;
				changemessagetype(message_type);
				
				//赋值
				$html.find("input[name='message_type'][value='"+message_type+"']").prop("checked",true);
				//发生变化
				$html.find('input[type=radio][name=message_type]').on('change keyup click', function () {
                    $span.attr('data-message_type', this.value || 1);
					var message_type = this.value;
					changemessagetype(message_type);
					var $input = $html.find('input,select');
					$input.on('change keyup click', function () {
						// 将input值写入到span上
						$span.data(this.name, $(this).val());
					});
                });
				



				//跳转链接赋值
				var customizeurl = $span.attr('data-customizeurl') || '';
				$html.find('#menu-customizeurl').val(customizeurl);
				$html.find('#menu-customizeurl').on('change keyup click', function () {
					$span.attr('data-'+this.name,this.value);
					var customizeurl = this.value;
					var $input = $html.find('input,select');
					$input.on('change keyup click', function () {
						// 将input值写入到span上
						$span.attr('data-'+this.name, $(this).val());
					});
				});
				
				//图文消息
				var rich_articles_data = $span.attr('data-rich_articles') || '';
				if (rich_articles_data.length>0)
				{
					rich_articles = JSON.parse(rich_articles_data);
					$("#graphic-title").text(rich_articles[0].title);
					$("#graphic-description").text(rich_articles[0].description);
					$("#graphic-url").text(rich_articles[0].url);
					$("#graphic-picurl").attr("src",rich_articles[0].picurl);
				}
				//文本消息
				entry_type = $span.attr('data-entry_type') || '1';
				var text_articles_data = $span.attr('data-text_articles') || '';
				console.log("初始化文本-------");
				console.log(text_articles_data.length);
				if (text_articles_data.length>0)
				{	
					text_articles = JSON.parse(text_articles_data);
				}else{
					text_articles = [{
						title: "{[此处输入互动内容](回复内容)}",
						description: '',
						url: ''
					}];
				}
				renderChange();

				//图片
				var msg_cover = $span.attr('data-msg_cover') || '';
				$("#msg-cover").attr("src",msg_cover)
            }


			function changemessagetype(message_type) {
				if (message_type==1)
				{
					$('#form-customizeurl').show();
					$('#form-graphic').hide();
					$('#form-text').hide();
					$('#form-image').hide();
				}else if(message_type==2){
					$('#form-customizeurl').hide();
					$('#form-graphic').show();
					$('#form-text').hide();
					$('#form-image').hide();
				}else if(message_type==3){
					$('#form-text').show();
					$('#form-customizeurl').hide();
					$('#form-graphic').hide();
					$('#form-image').hide();
				}else if(message_type==4){
					$('#form-image').show();
					$('#form-text').hide();
					$('#form-customizeurl').hide();
					$('#form-graphic').hide();
				}else{
					$('#form-customizeurl').hide();
					$('#form-graphic').hide();
					$('#form-image').hide();
				}

			}
        };

		

        menu.prototype.submit = function () {
            var data = [];
            $('li.parent-menu').map(function (index, item) {
                if (!$(item).hasClass('menu-add')) {
                    var menudata = getdata($(item).find('a:first span'));
                    menudata.index = index + 1;
                    menudata.pindex = 0;
                    menudata.sub = [];
                    menudata.sort = index;
                    data.push(menudata);
                    $(item).find('.sub-menu ul li:not(.menu-add) span').map(function (ii, span) {
                        var submenudata = getdata($(span));
                        submenudata.index = (index + 1) + '' + (ii + 1);
                        submenudata.pindex = menudata.index;
                        submenudata.sort = ii;
                        data.push(submenudata);
                    });
                }
            });
			
			

            $.post(editurl, {data: data},function(json){
				if(json.code==1)
				{
					updateAlert('菜单生成成功，大约5分钟后生效', 'success');
					setTimeout(function() {
						window.location.reload()
					}, 1000);
				}else{
					updateAlert('菜单生成失败'+json.msg, 'error');
					setTimeout(function() {
						//window.location.reload()
					}, 1000);
				}
			},'json');

            function getdata($span) {
                var menudata = {};
                menudata.name = $span.text();
                //menudata.type = $span.attr('data-type');
				menudata.message_type = $span.attr('data-message_type') || '1';
				menudata.entry_type = $span.attr('data-entry_type') || '1';
				if ($span.attr('data-message_type')==1)
				{
					menudata.url = $span.attr('data-customizeurl') || '';
				}else if($span.attr('data-message_type')==2)
				{
					menudata.param = $span.attr('data-rich_articles');
				}else if($span.attr('data-message_type')==3){
					menudata.param = $span.attr('data-text_articles');
				}else if($span.attr('data-message_type')==4){
					menudata.msg_cover = $span.attr('data-msg_cover') || '';
				}else{
					menudata.param = {};
					menudata.url = '';
					menudata.msg_cover = '';
				}
				/*
				if ($span.attr('data-type')>0)
				{
					menudata.url = arrayurl[menudata.type];
				}else{
					menudata.url = $span.attr('data-customizeurl') || '';
				}*/
                //console.log(menudata);
                return menudata;
            }
        };

		function renderChange() {
			var html = '';
			if (entry_type==2)
			{
				var total = text_articles.length;
				$("#text-add-sub").show();
				
				$.each(text_articles,function(index,value){
					html +='<div class="clearfix" style="margin-bottom: 10px;" id="text_list_'+index+'"><span id="text-title-'+index+'" style="color: black;">'+value.title+'</span>';
					
					html +='<a href="JavaScript:;" data-toggle="editSubArticle" data-index="'+index+'" title="修改"><i class="fa fa-edit"></i></a>';
					if (text_articles.length>1)
					{
						html +='<a href="JavaScript:;" id="text-remove" title="删除" data-index="'+index+'" class="text-danger"><i class="fa fa-trash-o"></i></a>';
						html +='<a href="JavaScript:;" id="text-upSub" data-index="'+index+'" title="上移" ><i class="glyphicon glyphicon-chevron-up"></i></a>';
					
						html +='<a href="JavaScript:;" id="text-downSub" title="下移" data-index="'+index+'" ><i class="glyphicon glyphicon-chevron-down"></i></a>';
					}else{
						html +='<a href="JavaScript:;" id="text-remove" title="删除" data-index="'+index+'" class="text-danger" style="display:none"><i class="fa fa-trash-o"></i></a>';

						html +='<a href="JavaScript:;" id="text-upSub" data-index="'+index+'" title="上移" style="display:none"><i class="glyphicon glyphicon-chevron-up"></i></a>';
					
						html +='<a href="JavaScript:;" id="text-downSub" title="下移" data-index="'+index+'" style="display:none"><i class="glyphicon glyphicon-chevron-down"></i></a>';
					}
						
					html +='<div id="text-url-'+index+'" style="color: #ccc;font-size: 12px;">'+value.url+'</div></div>';
				})
			}else{
				$("#text-add-sub").hide();
				$.each(text_articles,function(index,value){
					html +='<div class="clearfix" style="margin-bottom: 10px;" id="text_list"><span id="text-title" style="color: black;">'+value.title+'</span><a href="JavaScript:;" data-toggle="editSubArticle" data-index="'+index+'" title="修改"><i class="fa fa-edit"></i></a><a href="JavaScript:;" id="text-remove" title="删除" data-index="'+index+'" class="text-danger" style="display:none"><i class="fa fa-trash-o"></i></a><a href="JavaScript:;" id="text-upSub" data-index="'+index+'" title="上移" style="display:none"><i class="glyphicon glyphicon-chevron-up"></i></a><a href="JavaScript:;" id="text-downSub" title="下移" data-index="'+index+'" style="display:none"><i class="glyphicon glyphicon-chevron-down"></i></a><div id="text-url" style="color: #ccc;font-size: 12px;">'+value.url+'</div></div>';
				})

			}
			$("#text-msg-editor").html(html);

		};

		function imageupload(){
			/**
		  init: function (element, valueAccessor, allBindingsAccessor) {
			$(element).parent().find('.fa-spinner').hide();

			var url = $(element).data('url');
			var maxFileSize = 512 * 1024;

			var allBindings = allBindingsAccessor();
			var bindingOpts = allBindings.imageuploadOptions;

			if (bindingOpts) {
			  if (bindingOpts.url) {
				url = bindingOpts.url;
			  }
			  if (bindingOpts.maxFileSize) {
				maxFileSize = bindingOpts.maxFileSize;
			  }
			}

			var options = {
			  url: url,
			  dataType: 'json',
			  add: function (e, data) {
				var file = data.files[0];
				if (bindingOpts && bindingOpts.jsonSupport) {
					if (!(/\.json$/i).test(file.name)) {
						toastr.error('请选择json文件');
						return false;
					}
				} else {
					if (!(/\.(jpg|jpeg|png|gif)$/i).test(file.name)) {
						toastr.error('请选择图片文件');
						return false;
					}
					if (file.size > maxFileSize) {
						toastr.error('图片必须小于' + (maxFileSize / 1024) + 'KB');
						return false;
					}
				}

				$(e.target).parent().find('.fa-spinner').show();

				data.submit();
			  },
			  done: function (e, data) {
				$(e.target).parent().find('.fa-spinner').hide();
				valueAccessor()(data.result.url);
				toastr.success('上传成功');

				// 上传成功回调
				if (bindingOpts.callback) {
				  bindingOpts.callback(data.result);
				}
			  },
			  fail: function (e, data) {
				$(e.target).parent().find('.fa-spinner').hide();
				handleAjaxError(data.jqXHR);
			  }
			};
			$(element).fileupload(options);
		  }
		  */
		};

        new menu();
    });